package com.polaris.live.ui.backpack.fragment

import android.os.Bundle
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.adapter.backpack.BackPackNumberAdapter
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.FragmentNumberBinding
import com.polaris.live.interface_bag.BackPackNumberCallback
import com.polaris.live.interface_bag.BackPackNumberImpl
import com.polaris.live.resp.back_resp.UserBackpackNumberResp
import com.polaris.live.translation.R.string
import com.polaris.live.viewmodel.backpack.BackPackNumberViewModel
import com.polaris.live.widget.refresh.EmptyView

/**
 * BackpackNumberFragment 靓号
 *
 * @author Created by 天晴 on 2024/9/19/031 17:43
 */
class BackpackNumberFragment : BaseVbFragment<BackPackNumberViewModel, FragmentNumberBinding>(),
    BackPackNumberImpl {

    private val mType: Long by lazy {
        arguments?.getLong("type") ?: 0L
    }

    private val mAdapter by lazy { BackPackNumberAdapter() }

    private var mBackPackNumberCallback: BackPackNumberCallback? = null

    private val emptyView by lazy { EmptyView(requireContext()) }

    private var mFirstVisiblePosition = 0
    private var mLastVisiblePosition = 0
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.root.post {
            emptyView.setEmptyTip(R.drawable.family_empty, StringUtils.getString(string.no_hava_data))
            emptyView.layoutParams = ViewGroup.LayoutParams(mBinding.root.width, mBinding.root.height)
            mAdapter.setEmptyView(emptyView)
        }
        val numberOfColumns = 3
        mBinding.recyclerView.layoutManager = GridLayoutManager(requireContext(), numberOfColumns)
        mBinding.recyclerView.adapter = mAdapter
        mBinding.recyclerView.itemAnimator = null
        mBinding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                mBinding.recyclerView.post {
                    checkVisibleItems()
                }
            }
        })
        mBinding.swipe.setOnRefreshListener {
            mViewModel.getNumberList()
        }
        mBinding.swipe.setEnableLoadMore(false)
        initListener()
        initObserver()
    }

    private fun checkVisibleItems() {
        val layoutManager = mBinding.recyclerView.layoutManager as LinearLayoutManager
        val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition()
        val lastVisiblePosition = layoutManager.findLastVisibleItemPosition()
        if (mFirstVisiblePosition != firstVisiblePosition || lastVisiblePosition != mLastVisiblePosition) {
            if (firstVisiblePosition > mFirstVisiblePosition) {
                for (i in mFirstVisiblePosition until firstVisiblePosition) {
                    mAdapter.notifyItemChanged(i, "hide")
                }
            }
            if (firstVisiblePosition < mFirstVisiblePosition) {
                for (i in firstVisiblePosition until mFirstVisiblePosition) {
                    mAdapter.notifyItemChanged(i, "show")
                }
            }
            if (lastVisiblePosition > mLastVisiblePosition) {
                for (i in mLastVisiblePosition + 1..lastVisiblePosition) {
                    mAdapter.notifyItemChanged(i, "show")
                }
            }
            if (lastVisiblePosition < mLastVisiblePosition) {
                for (i in lastVisiblePosition + 1..mLastVisiblePosition) {
                    mAdapter.notifyItemChanged(i, "hide")
                }
            }
            mFirstVisiblePosition = firstVisiblePosition
            mLastVisiblePosition = lastVisiblePosition

        }
    }

    /**
     * 定时刷新
     */
    fun timerUpdate() {
        if (!isCreated()) {
            return
        }
        mBinding.recyclerView.post {
            // 收集需要删除的索引
            val indicesToRemove = mutableListOf<Int>()
            val nowServerTime = CacheUtil.getServerTime()
            mAdapter.data.forEachIndexed { index, item ->
                when {
                    item.expiredTime == null -> {} // 永久物品
                    item.expiredTime.toLong() - nowServerTime > 0 -> {
                        mAdapter.notifyItemChanged(index, "notify")
                    } // 未超时 刷新时间
                    else -> {
                        indicesToRemove.add(index)
                    }
                }
            }
            indicesToRemove.sortedDescending().forEach { index ->
                mAdapter.removeAt(index)
            }
        }
    }

    /**
     * 更新数据
     */
    fun updateData(type: Long) {
        if (!isCreated()) {
            return
        }
        if (mType == type) {
            mViewModel.getNumberList()
        }
    }

    private fun initObserver() {
        mViewModel.mNumberLiveData.observe(this) { resultState ->
            mBinding.swipe.finishRefresh()
            parseState(resultState, { resultData ->
                mAdapter.setList(resultData)
            })
        }
        mViewModel.mUseNumberLiveData.observe(this) { resultState ->
            parseState(resultState, { resultData ->
                mViewModel.getNumberList()
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private fun initListener() {
        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.data[position]
            mAdapter.setSelect(position)
            mBackPackNumberCallback?.onBackPackSelectCallback(item)
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.data[position]
            when (view.id) {
                R.id.tv_chick -> {
                    mViewModel.useNumber(item.userNumber, AppConst.YESLONG)
                    mAdapter.setSelect(position)
                    mBackPackNumberCallback?.onBackPackSelectCallback(item)
                }
                R.id.tv_chick1 -> {
                    mViewModel.useNumber(item.userNumber, AppConst.NOLONG)
                }
            }
        }

    }

    override fun onBackPackDataCallback(backPackList: List<UserBackpackNumberResp>) {
        mAdapter.setList(backPackList)
    }

    override fun onBackPackSelectCallback(position: Int) {
        if (mAdapter.getLastSelect() == position) return
        mAdapter.setSelect(position)
    }

    fun setBackPackNumberCallback(l: BackPackNumberCallback) {
        mBackPackNumberCallback = l
    }

    override fun onResume() {
        super.onResume()
        if (mAdapter.data.isEmpty()) {
            mBackPackNumberCallback?.onBackPackSelectCallback(null)
        }
        mBinding.root.post {
            val index = mAdapter.getLastSelect()
            if (index == -1) {
                val orNull = mAdapter.data.getOrNull(0) ?: return@post
                mAdapter.setSelect(0)
                mBackPackNumberCallback?.onBackPackSelectCallback(orNull)
            } else {
                val orNull = mAdapter.data.getOrNull(index) ?: return@post
                mBackPackNumberCallback?.onBackPackSelectCallback(orNull)
            }
        }
    }

    fun getType(): Long {
        return mType
    }

    override fun onDestroy() {
        super.onDestroy()
        mBackPackNumberCallback = null
    }
}